﻿using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Liphofra.Core;

namespace Liphofra.Mvvm.ViewModels
{
    /// <summary>
    /// A base class with common logic and features for all sorts of view models, including notification changed events and disposal.
    /// </summary>
    public abstract class ViewModelBase : IViewModel 
    {
        /// <summary>
        /// Gets or sets the service locator to use for dependency resolution.
        /// </summary>
        public IServiceLocator ServiceLocator
        {
            get;
            set;
        }

        #region INotifyPropertyChanged

        /// <summary>
        /// Occurs when a property has changed.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Called when a property has changed and the corresponding <see cref="PropertyChanged"/> event should be raised.
        /// Must be called by derived classes to preserve correct notification support.
        /// </summary>
        /// <param name="propertyName">The name of the property that has changed.</param>
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region IDisposable

        private bool _isDisposed;

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        private void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                if (disposing)
                {
                    // dispose managed resources
                    OnDispose();
                }

                // release any unmanaged resources here
            }

            _isDisposed = true;
        }

        /// <summary>
        /// Called when the instance should dispose any managed resources.
        /// </summary>
        protected virtual void OnDispose()
        {
        }

        #endregion
    }
}